package cn.huangsm.advance.mongodb;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 * @author huang
 * @PACKAGE_NAME cn.huangsm.advance.mongodb
 * @PROJECT_NAME advance-code
 * @date 2019/1/24
 */
@Service("mongoUserService")
public class UserService {
    @Autowired
    private UserDao userDao;

    public User findUserById(String id){
        return userDao.findAllBy_id(id);
    }
    public void save(User user){
        user.set_id(UUID.randomUUID().toString());
        userDao.save(user);
    }
    @Autowired
    private MongoTemplate mongoTemplate;

    public void update(User user){
        Query query=new Query();
        query.addCriteria(Criteria.where("name").is(user.getName()));
        Update update=new Update();
        update.set("image",user.getImage());
        mongoTemplate.updateFirst(query,update,User.class);
    }

    public void del(String id) {

        Query query=new Query().addCriteria(Criteria.where("_id").is(id));
        mongoTemplate.remove(query,User.class);
    }

    public List<User> list() {
       return  mongoTemplate.findAll(User.class);
    }
}
